/**
 * 项目设置 编辑页
 *
 * 作者 admin
 * 日期 2024-07-29 14:19:15
 */
layui.use(['jquery','laydate','febs', 'form', 'validate','table', 'commonJS','autocomplete'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        laydate = layui.laydate,
        form = layui.form,
        formSelects = layui.formSelects,
        table = layui.table,
        commonJS = layui.commonJS,
        $view = $('#baseProject-edit'),
        $safetyManage = $('#safetyManage'),
        $addRelation = $('#addRelation'),
        $projectManage = $('#projectManage'),
        currentTenantId = POPUP_DATA.tenantId,
        validate = layui.validate,
        autocomplete = layui.autocomplete,
        $projectType = $view.find('#projectType'),
        tableIns;

        let projectUserTableData = [];
        let chooseUser = {};

    initDictItemSelect_projectList();
    form.verify(validate);
    form.render();

    initFormValue();

    initRelationPersonTable();

    form.verify({
        english: function(value, item){
            if(!/^[A-Za-z0-9]+$/.test(value)){
                return '输入内容必须为英文字母或数字';
            }
        },
        chinese: function(value, item){
            if(!/^[\u4e00-\u9fa50-9]+$/.test(value)){
                return '输入内容必须为中文字符或数字';
            }
        }
    });

    function initDictItemSelect_projectList(){
        // 项目类型
        febs.initDictItemSelect($projectType,'SAFETY_PROJECT_TYPE', baseProjectData.projectType,null);
    }

    formSelects.render();
    // 项目负责人
    $('#inputAuto').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName:'keywords',
        useType:'user',
        params:{ tenantId: currentTenantId},
        onSelect: function(suggestion) {
            chooseUser.projectManageId = suggestion.userId;
            chooseUser.projectManageName = suggestion.value;
            chooseUser.projectManagePhone = suggestion.mobile;
            $view.find("input[name=projectManageName]").val(chooseUser.projectManageName);
        },
    });
    // 安全负责人
    $('#inputAutoSafe').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName:'keywords',
        useType:'user',
        params:{ tenantId: currentTenantId},
        onSelect: function(suggestion) {
            chooseUser.safetyManageId = suggestion.userId;
            chooseUser.safetyManageName = suggestion.value;
            chooseUser.safetyManagePhone = suggestion.mobile;
            $view.find("input[name=safetyManageName]").val(chooseUser.safetyManageName);
        },
    });
    formSelects.config('project-area-select', {
        searchUrl: ctx + 'baseArea',
        data: {
            tenantId: currentTenantId
        },
        response: {
            statusCode: 200
        },
        beforeSuccess: function (id, url, searchVal, result) {
            var data = result.data;
            var tranData = [];
            for (var i = 0; i < data.length; i++) {
                tranData.push({
                    name: data[i].areaName,
                    value: data[i].areaId
                })
            }
            result.data = tranData;
            return result;
        },
        success: function () {
            if(baseProjectData && baseProjectData.areaId != null){
                formSelects.value('project-area-select', baseProjectData.areaId.split(','));
            }
        },
        error: function (id, url, searchVal, err) {
            console.error(err);
            febs.alert.error('获取区域列表失败');
        }
    });
    // 项目类型
    formSelects.config('project-area-select', {
        searchUrl: ctx + 'baseArea',
        data: {
            tenantId: currentTenantId
        },
        response: {
            statusCode: 200
        },
        beforeSuccess: function (id, url, searchVal, result) {
            var data = result.data;
            var tranData = [];
            for (var i = 0; i < data.length; i++) {
                tranData.push({
                    name: data[i].areaName,
                    value: data[i].areaId
                })
            }
            result.data = tranData;
            return result;
        },
        success: function () {
            if(baseProjectData && baseProjectData.areaId != null){
                formSelects.value('project-area-select', baseProjectData.areaId.split(','));
            }
        },
        error: function (id, url, searchVal, err) {
            console.error(err);
            febs.alert.error('获取区域列表失败');
        }
    });
    function initRelationPersonTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'projectUserTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            // height: 'auto',
            css: [ // 设置单元格样式
                // 取消默认的溢出隐藏，并设置适当高度
                '.layui-table-cell{height: 50px; line-height: 40px;}',
                '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                '.layui-table-cell select{height: 36px; padding: 0 5px;}'
            ].join(''),
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'userId', title: 'id',hide:true},
                {field: 'realName',align:'center', title: '姓名', minWidth: 100},
                {field: 'projectUserType',align:'center',title: '人员类型', minWidth: 100,edit: 'text'},
                {field: 'contactsPhone',align:'center', title: '联系方式', minWidth: 150},
                {title: '操作',align:'center', toolbar: '#project-user-option', width: 80}
            ]],
            done: function(res, curr, count){
                var options = this;
                $view.find('.layui-table-body, .layui-table-box, .layui-table-cell').css('overflow', 'visible')
                var allCol= $view.find('#projectUserTable .layui-table-body, .layui-table-box tbody .layui-table-cell')
                for(var i=0;i<allCol.length;i++){
                    var isSelect = $(allCol[i]).find("select[name='projectUserType']")
                    if(isSelect.length==0){
                        $(allCol[i]).css('overflow', 'hidden')
                    }
                }

                // 获取当前行数据 - 自定义方法
                table.getRowData = function(tableId, elem){
                    var index = $(elem).closest('tr').data('index');
                    return table.cache[tableId][index] || {};
                };

                // layui table select 事件
                form.on('select(projectUserType)', function(obj){
                    // 获取选中项 value
                    var userType = obj.value;
                    // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                    var data = table.getRowData(options.id, obj.elem);
                    //修改对应数据的用户类型
                    changeProjectUserType(data.userId,userType);
                    console.log(JSON.stringify(projectUserTableData))
                });
                form.render();
            },
            data:projectUserTableData
        });
        // tableIns.reload({data:projectUserTableData});
    }
    function changeProjectUserType(userId,selectVal){
        for (var i = 0; i < projectUserTableData.length; i++) {
            if (projectUserTableData[i]['userId'] === userId) {
                projectUserTableData[i]['projectUserType'] = selectVal;
            }
        }
    }
    function reloadTab(data){
        tableIns.reload({data:data});
    }

    $addRelation.on('click', function () {
        febs.modal.open('其他关联人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:currentTenantId,
                selectList:projectUserTableData,
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                for (var i = 0; i < selectData.length; i++) {
                    var temp = {};
                    temp.userId = selectData[i].userId;
                    temp.tenantId = currentTenantId;
                    temp.userName = selectData[i].userName;
                    temp.realName = selectData[i].uname;
                    temp.contactsPhone = selectData[i].mobile;
                    //默认为'1':建造经理，table中select选择时重新给值
                    temp.projectUserType = '';
                    if(isRepeat(projectUserTableData,selectData[i].userId)){
                        febs.alert.warn("用户"+selectData[i].uname+"已添加!");
                        return false;
                    }
                    projectUserTableData.push(temp);
                }

                reloadTab(projectUserTableData);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });
    function isRepeat(arr,userId) {
        for (var i = 0; i < arr.length; i++) {
                if (arr[i]['userId'] === userId) {
                    return true;
                }
        }
        return false;
    }
    $safetyManage.on('click', function () {
        febs.modal.open('安全负责人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:currentTenantId,
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                chooseUser.safetyManageId = selectData.userId;
                chooseUser.safetyManageName = selectData.uname;
                chooseUser.safetyManagePhone = selectData.mobile;
                $view.find("input[name=safetyManageName]").val(chooseUser.safetyManageName);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    $projectManage.on('click', function () {
        febs.modal.open('项目负责人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:currentTenantId,
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                chooseUser.projectManageId = selectData.userId;
                chooseUser.projectManageName = selectData.uname;
                chooseUser.projectManagePhone = selectData.mobile;
                $view.find("input[name=projectManageName]").val(chooseUser.projectManageName);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    table.on('tool(projectUserTable)', function (obj) {
        var data = obj.data,
            that = this,
            tr = obj.tr,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                var cacheData = layui.table.cache['projectUserTable'];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                projectUserTableData = cacheData;
                reloadTab(projectUserTableData);
                layer.close(index);//关闭弹窗
            });
        }
    });

    function initFormValue() {

        if (baseProjectData && baseProjectData.projectId) {
            //关联人员
            projectUserTableData = baseProjectData.baseProjectUserList ? baseProjectData.baseProjectUserList : [];
            form.val("baseProject-edit-form", {
                "projectId": baseProjectData.projectId,
                "tenantId": baseProjectData.tenantId,
                "projectName": baseProjectData.projectName,
                "projectNameEn": baseProjectData.projectNameEn,
                "projectCode": baseProjectData.projectCode,
                "sort": baseProjectData.sort,
                "projectType": baseProjectData.projectType,
                "startDate": baseProjectData.startDate,
                "endDate": baseProjectData.endDate,
                "projectManageId": baseProjectData.projectManageId,
                "projectManageName": baseProjectData.projectManageName,
                "projectManagePhone": baseProjectData.projectManagePhone,
                "safetyManageId": baseProjectData.safetyManageId,
                "safetyManageName": baseProjectData.safetyManageName,
                "safetyManagePhone": baseProjectData.safetyManagePhone,
                "status": baseProjectData.status,
            });
            form.render('select');
        }
    }

    form.on('submit(baseProject-edit-form-submit)', function (data) {
        data.field.tenantId = currentTenantId
        Object.assign(data.field,chooseUser);
        data.field.baseProjectUserList = projectUserTableData;
        console.log(data.field);
        addOrUpdate(data.field);
        return false;
    });
    function addOrUpdate(data) {
        if (data.projectId && data.projectId.length > 0) {
            febs.modal.confirm('修改项目','确定修改项目？', function (index) {
                febs.postArray(ctx + 'baseProject/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('修改成功');
                    $('#febs-baseProject').find('#query').trigger('click');
                });
            });

        } else {
            febs.modal.confirm('保存项目信息','确定保存项目信息？', function (index) {
                febs.postArray(ctx + 'baseProject', data, function () {
                    layer.closeAll();
                    febs.alert.success('新增成功');
                    $('#febs-baseProject').find('#query').trigger('click');
                });
            });

        }
    }
    laydate.render({
        elem: "#startDate", done: function (value, date) {
            if ($("#endDate").val() && value > $("#endDate").val()) {
                febs.alert.warn('开始时间不能大于结束时间');
                $("#startDate").val("");
            }
        },
    });

    laydate.render({
        elem: "#endDate", done: function (value, date) {
            if ($("#startDate").val() && value < $("#startDate").val()) {
                febs.alert.warn('结束时间不能小于开始时间');
                $("#endDate").val("");
            }
        },
    });


});